package org.murillo.chufa.datastructures;

import org.murillo.chufa.entry.CacheEntry;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections4.map.LRUMap;

public class LRUWeakIdentityHashMap<K, V extends CacheEntry> implements Map<K, V> {

    private final ReferenceQueue<K> queue;
    private final Map<IdentityWeakReference, V> map;
    private final int sizelimit;

    public LRUWeakIdentityHashMap(/*int hardCapacity, */int maxsize, float f) {
        this.queue = new ReferenceQueue<K>();
        this.sizelimit = maxsize;
        this.map = new LRUMap<IdentityWeakReference, V>(maxsize, f, true) {
            @Override
            protected boolean removeLRU(LinkEntry<IdentityWeakReference, V> eldest) {
                if (size() >= sizelimit) {
                    if (eldest.getValue().getHard() == null) {
                        eldest.getValue().dispose();
                        return true;
                    }
                }
                return false;
            }
        };
    }

    @Override
    public void clear() {
        map.clear();
        runMaintenance();
    }

    @Override
    public boolean containsKey(Object key) {
        runMaintenance();
        return map.containsKey(new IdentityWeakReference(key));
    }

    @Override
    public boolean containsValue(Object value) {
        runMaintenance();
        return map.containsValue(value);
    }

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
        runMaintenance();
        Set<Map.Entry<K, V>> ret = new HashSet<Map.Entry<K, V>>();
        for (Map.Entry<IdentityWeakReference, V> ref : map.entrySet()) {
            final K key = ref.getKey().get();
            final V value = ref.getValue();
            Map.Entry<K, V> entry = new Map.Entry<K, V>() {
                @Override
                public K getKey() {
                    return key;
                }

                @Override
                public V getValue() {
                    return value;
                }

                @Override
                public V setValue(V value) {
                    throw new UnsupportedOperationException();
                }
            };
            ret.add(entry);
        }
        return Collections.unmodifiableSet(ret);
    }

    @Override
    public Set<K> keySet() {
        runMaintenance();
        Set<K> ret = new HashSet<K>();
        for (IdentityWeakReference ref : map.keySet()) {
            ret.add(ref.get());
        }
        return Collections.unmodifiableSet(ret);
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof LRUWeakIdentityHashMap)) {
            return false;
        }
        LRUWeakIdentityHashMap<?, ?> v = (LRUWeakIdentityHashMap<?, ?>) o;
        return map.equals(v.map);
    }

    @Override
    public V get(Object key) {
        runMaintenance();
        return map.get(new IdentityWeakReference(key));
    }

    @Override
    public V put(K key, V value) {
        runMaintenance();
        return map.put(new IdentityWeakReference(key), value);
    }

    @Override
    public int hashCode() {
        runMaintenance();
        return map.hashCode();
    }

    @Override
    public boolean isEmpty() {
        runMaintenance();
        return map.isEmpty();
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> t) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(Object key) {
        runMaintenance();
        return map.remove(new IdentityWeakReference(key));
    }

    @Override
    public int size() {
        runMaintenance();
        return map.size();
    }

    @Override
    public Collection<V> values() {
        runMaintenance();
        return map.values();
    }

    private void runMaintenance() {
        Reference<? extends K> zombie = queue.poll();

        while (zombie != null) {
            map.remove(zombie);
            zombie = queue.poll();
        }
    }

    public class IdentityWeakReference extends WeakReference<K> {

        int hash;

        @SuppressWarnings("unchecked")
        IdentityWeakReference(Object obj) {
            super((K) obj, queue);
            hash = System.identityHashCode(obj);
        }

        public int hashCode() {
            return hash;
        }

        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o instanceof WeakReference) {
                WeakReference<?> ref = (WeakReference<?>) o;
                if (this.get() == ref.get()) {
                    return true;
                }
            }
            return false;
        }
    }
}
